package org.hwua.production.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.hwua.production.domain.custom.ActiveUser;
import org.hwua.production.service.SysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

 /**
  * created on 2017年2月6日 
  *
  * 登陆和退出控制层
  *
  * @author  hwua
  * @version  1.0.0
  */
@Controller
public class LoginController {
	
	@Autowired
	private SysService sysService;
	
	
	//用户登陆提交方法
	/**
	 * 
	 * <p>Title: login</p>
	 * <p>Description: </p>
	 * @param session
	 * @param randomcode 输入的验证码
	 * @param usercode 用户账号
	 * @param password 用户密码 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public @ResponseBody Map<String,Object> login(HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		Map<String,Object> map = new HashMap<String,Object>();  
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		//从服务器缓存中拿出先前放置的验证码
		String sessionCode=(String)request.getSession().getAttribute("code");
		
		if(!sessionCode.equals(code)){//与页面传过来的验证码对比
			map.put("msg", "验证码错误！");
			return map; 
		}
		
		//调用service校验用户账号和密码的正确性
		ActiveUser activeUser = sysService.authenticat(username, password);
		
		if(activeUser!=null){
			//如果service校验通过，将用户身份记录到session
			session.setAttribute("activeUser", activeUser);
			//重定向到商品查询页面
			map.put("msg", "success");
		}else{
			map.put("msg", "用户名或密码错误！");
		}
		
		Subject currentUser = SecurityUtils.getSubject();
	    if (!currentUser.isAuthenticated()) {
	    	
	    	UsernamePasswordToken token = new UsernamePasswordToken(username, password);
	         
	        try{
	            currentUser.login(token);
	        }catch(UnknownAccountException ex){
	        	map.put("msg", "account_error");
	        }catch(IncorrectCredentialsException ex){
	        	map.put("msg", "password_error");
	        }catch(AuthenticationException ex){
	        	map.put("msg", "authentication_error");
	        }
	    }
	    
		return map; 
	}
	
	/**
	 * 生成验证码
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/code")
	public void code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//在内存中创建图像
		int width=60,height=20;
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//获取图形上下文
		Graphics g=image.getGraphics();
		//创建随机数对象
		Random random=new Random();
		//设定背景色
		g.setColor(getRandColor(200,250));
		g.fillRect(0, 0, width, height);
		
		//设置字体
		g.setFont(new Font("Times New Roman",Font.PLAIN,18));
		
		//随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		g.setColor(getRandColor(60,200));
		for(int i=0;i<155;i++){
			int x=random.nextInt(width);
			int y=random.nextInt(height);
			int xl=random.nextInt(12);
			int yl=random.nextInt(12);
			g.drawLine(x, y, x+xl, y+yl);
		}
		
		//随机产生认证码(4位数字)
		String sRand="";
		for(int i=0;i<4;i++){
			String rand=String.valueOf(random.nextInt(10));
			sRand+=rand;
			//将认证码显示到图象中
			g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
			g.drawString(rand, 13*i+6, 16);
		}
		
		//将认证码存入SESSION
		request.getSession().setAttribute("code", sRand);
		//图象生效
		g.dispose();
		
		ByteArrayOutputStream output=new ByteArrayOutputStream();
		ImageOutputStream imageOut=ImageIO.createImageOutputStream(output);
		ImageIO.write(image, "JPEG", imageOut);
		imageOut.close();
		response.getOutputStream().write(output.toByteArray());
	}
	
	private Color getRandColor(int fc,int bc){
		//创建随机数对象
		Random random=new Random();
		if(fc>255){
			fc=255;
		}
		
		if(bc>255){
			bc=255;
		}
		
		int r=fc+random.nextInt(bc-fc);
		int g=fc+random.nextInt(bc-fc);
		int b=fc+random.nextInt(bc-fc);
		return new Color(r,g,b);
	}
	
	//用户退出
	@RequestMapping("/logout")
	public String logout(HttpSession session)throws Exception{
		SecurityUtils.getSubject().getSession().setTimeout(0);
		//session失效
		session.invalidate();
		//重定向到商品查询页面
		return "redirect:/first.action";
		
	}
}
